package fun.codefarmer.pm.controller.management;

import fun.codefarmer.pm.constant.Constant;
import fun.codefarmer.pm.dto.UploadDto;
import fun.codefarmer.pm.model.RespBean;
import fun.codefarmer.pm.model.Result;
import fun.codefarmer.pm.utils.fileUtil.FileNameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @ ClassName ImgUpload
 * @ Descriotion TODO
 * @ author  codeFarmer_z
 * @ 公众号：码农教程
 * @ Date 2022/5/11 21:07
 **/
@Controller
@RequestMapping("/system/hr")
public class ImgUpload {
    @Value("${web.profile}")
    private String path;
    @PostMapping("/imgUpload")
    @ResponseBody
    public RespBean imgUpload(@RequestParam MultipartFile file) {

        if (file.isEmpty()) {
            return RespBean.error("文件不能为空");
        }
        try {
            //1.定义上传的文件
            String localPath = path;
            //2.获得文件名字
            String fileName = file.getOriginalFilename();
            //3.上传

            //3.1 生成新的文件路径和文件名
            String realPath =  FileNameUtils.datePath() + File.separator + FileNameUtils.getFileName(fileName);
            // 保存的文件及文件地址
            String savePath = localPath + File.separator + realPath;
            //3.2 保存文件
            File dest = new File(savePath);
            //判断文件目目录是否存在,不存在则新建
            if (!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);

            //保存路径到数据库
            String url = Constant.RESOURCE_PREFIX + File.separator + realPath;
            UploadDto uploadDto = new UploadDto();
            uploadDto.setFileName(fileName);
            uploadDto.setUrl(url);
            return RespBean.ok("上传成功",uploadDto);

        } catch (Exception e) {
            e.printStackTrace();
            return RespBean.error("文件上传失败");
        }
    }
    @PostMapping("/test")
    @ResponseBody
    public String test() {
        return path;

    }
}
